package com.cy.aircompressor.main.home.lifecycle.child;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.RelativeLayout;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.cy.aircompressor.config.AirConfig;
import com.cy.aircompressor.databinding.AirSensorManagerHeadBinding;
import com.cy.aircompressor.databinding.ChildDialogContainerBinding;
import com.cy.aircompressor.databinding.PageTurningIndicatorContainerBinding;
import com.cy.aircompressor.entity.compressor.Compressor;
import com.cy.aircompressor.entity.select.SelectDict;
import com.cy.aircompressor.entity.sensor.Sensor;
import com.cy.aircompressor.main.home.fragment.v2.MainContentHelperV2;
import com.cy.aircompressor.main.home.lifecycle.provider.SensorManagerProvider;
import com.cy.aircompressor.main.ui.lifecycle.viewmodel.LifeCycleViewModel;
import com.cy.aircompressor.main.view.PageTurningIndicator;
import com.cy.aircompressor.main.view.pop.AirDropdownPopupWindow;
import com.cy.aircompressor.main.view.pop.AirDropdownPopupWindowV2;
import com.drug.lib.util.ToastUtil;
import com.drug.lib.view.recycptr.DynamicAdpTypePool;
import com.drug.lib.view.recycptr.DynamicRecyclerAdapter;
import com.drug.lib.view.recycptr.bean.RowEntity;
import com.jakewharton.rxbinding2.view.RxView;
import com.net.model.base.Resource;
import com.net.model.base.fragment.BaseVMFragment;
import com.net.model.utils.Constant;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public class SensorManagerFragment extends BaseVMFragment<ChildDialogContainerBinding, LifeCycleViewModel> {
    private Integer pageNum = 1;
    private Integer pageSize = 10;
    private Integer pageTotal = 1;
    private String powerStationId;
    private String airCompressorId;
    private String sensorSn;
    private Integer sensorType;

    public static SensorManagerFragment newInstance() {
        Bundle args = new Bundle();
        SensorManagerFragment fragment = new SensorManagerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void dataChange() {
        powerStationId = AirConfig.get().userInfo.getPowerStationId();
        mViewModel.getQuerySensorByPageObservable().observe(this, new Observer<Resource<RowEntity<Sensor>>>() {
            @Override
            public void onChanged(Resource<RowEntity<Sensor>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<RowEntity<Sensor>>() {
                    @Override
                    public void onSuccess(RowEntity<Sensor> data) {
                        footBinding.indicator.setRecordTotal(data.getTotal());
                        dynamicRecyclerAdapter.setItems(data.getList());
                        dynamicRecyclerAdapter.notifyDataSetChanged();
                        mBinding.nodata.dismiss();
                    }

                    @Override
                    public void onFailure(Integer code, String message) {
                        super.onFailure(code, message);
                        if (code == Constant.EMPTY_DATA_ERROR) {
                            dynamicRecyclerAdapter.setItems(new ArrayList<>());
                            dynamicRecyclerAdapter.notifyDataSetChanged();
                            mBinding.nodata.show();
                        }
                    }
                });
            }
        });

        mViewModel.getCompressorObservable().observe(this, new Observer<Resource<RowEntity<Compressor>>>() {
            @Override
            public void onChanged(Resource<RowEntity<Compressor>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<RowEntity<Compressor>>() {
                    @Override
                    public void onSuccess(RowEntity<Compressor> data) {
                        AirDropdownPopupWindowV2 mPopupWindow = new AirDropdownPopupWindowV2(mContext, headBinding.selectedAir, headBinding.selectedAir, data.getList());
                        mPopupWindow.setDropdownCallBack(new AirDropdownPopupWindowV2.DropdownCallBack() {
                            @Override
                            public void select(Compressor compressor) {
                                SensorManagerFragment.this.airCompressorId = compressor.getId();
                                requestNetwork();
                            }
                        });
                        mPopupWindow.showAsDropDown(headBinding.selectedAir);//显示PopupWindow小弹窗
                    }

                    @Override
                    public void onFailure(Integer code, String message) {
                        super.onFailure(code, message);
                        if (code == Constant.EMPTY_DATA_ERROR) {
                            ToastUtil.show("该电站未安装有空压机");
                        }
                    }
                });
            }
        });
    }

    @Override
    protected ChildDialogContainerBinding getViewBinding() {
        return ChildDialogContainerBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        headView();
        setSelectDict();
        footView();
        initRecyclerAdapter();
    }

    @Override
    protected void requestNetwork() {
        mViewModel.querySensorByPage(pageNum, pageSize, airCompressorId, powerStationId, sensorSn, sensorType);
    }
    private void setSelectDict() {
        List<SelectDict> compressors = AirConfig.get().compressors;
        compressors.forEach(new Consumer<SelectDict>() {
            @Override
            public void accept(SelectDict dict) {
                if (TextUtils.equals(dict.getValue(), MainContentHelperV2.get().currentCompressor.getId())) {
                    airCompressorId = dict.getValue();
                    headBinding.selectedAir.setText(dict.getLabel());
                }
            }
        });
    }
    AirSensorManagerHeadBinding headBinding;

    private void headView() {
        headBinding = AirSensorManagerHeadBinding.inflate(getLayoutInflater());
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        mBinding.airBaseHead.addView(headBinding.getRoot(), layoutParams);
        headBinding.addSensor.setText("+ 新增");
        headBinding.selectedPowerStation.setText(AirConfig.get().userInfo.getPowerStationName());

        RxView.clicks(headBinding.selectedPowerStation)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    AirDropdownPopupWindow mPopupWindow = new AirDropdownPopupWindow(mContext, headBinding.selectedPowerStation, headBinding.selectedPowerStation, AirConfig.get().powerStations);
                    mPopupWindow.setDropdownCallBack(new AirDropdownPopupWindow.DropdownCallBack() {
                        @Override
                        public void select(SelectDict selectDict) {
                            SensorManagerFragment.this.powerStationId = selectDict.getValue();
                            headBinding.selectedAir.setText("");
                            SensorManagerFragment.this.airCompressorId = null;
                            requestNetwork();
                        }
                    });
                    mPopupWindow.showAsDropDown(headBinding.selectedPowerStation);//显示PopupWindow小弹窗
                });
        RxView.clicks(headBinding.selectedAir)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    mViewModel.compressor(1, 100, powerStationId, null);
                });
        RxView.clicks(headBinding.selectedSensorType)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    AirDropdownPopupWindow mPopupWindow = new AirDropdownPopupWindow(mContext, headBinding.selectedSensorType, headBinding.selectedSensorType, AirConfig.get().sensorTypes);
                    mPopupWindow.setDropdownCallBack(new AirDropdownPopupWindow.DropdownCallBack() {
                        @Override
                        public void select(SelectDict selectDict) {
                            SensorManagerFragment.this.sensorType = Integer.parseInt(selectDict.getValue());
                            requestNetwork();
                        }
                    });
                    mPopupWindow.showAsDropDown(headBinding.selectedSensorType);//显示PopupWindow小弹窗
                });
        RxView.clicks(headBinding.searchButton)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    sensorSn = headBinding.airSn.getText().toString().trim();
                    if (TextUtils.isEmpty(sensorSn)) return;
                    requestNetwork();
                });
    }


    PageTurningIndicatorContainerBinding footBinding;

    private void footView() {
        footBinding = PageTurningIndicatorContainerBinding.inflate(getLayoutInflater());
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        mBinding.airBaseBottom.addView(footBinding.getRoot(), layoutParams);
        footBinding.indicator.setPageNum(pageNum);
        footBinding.indicator.setPageSize(pageSize);
        footBinding.indicator.setPageTurningIndicatorCallBack(new PageTurningIndicator.PageTurningIndicatorCallBack() {
            @Override
            public void skipPage(int page) {
                pageNum = page;
                requestNetwork();
            }

            @Override
            public void pageSize(int size) {
                pageSize = size;
                requestNetwork();
            }
        });
    }

    DynamicRecyclerAdapter dynamicRecyclerAdapter;

    private void initRecyclerAdapter() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.recyclerView.setLayoutManager(mLayoutManager);
        dynamicRecyclerAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        SensorManagerProvider sensorManagerProvider = new SensorManagerProvider(mContext,getChildFragmentManager());
        pool.register(Sensor.class, sensorManagerProvider);
        dynamicRecyclerAdapter.registerAll(pool);
        mBinding.recyclerView.setAdapter(dynamicRecyclerAdapter);
    }
}
